package java_DesignPattern.CreatorPattern.SingletonPattern.tryDestruction.serialization;

import java.io.Serializable;

/**
 * 通过序列化来破环单例模式
 * 以静态内部类为例(其余方式也可被破坏),仅有枚举可以避免
 */
public class Singleton implements Serializable {

    private static final long serialVersionUID = 1L;

    //私有化构造方法
    private Singleton(){
    }

    private static class SingletonHolder{

        //声明静态的实例
        private static final Singleton singleton = new Singleton();
    }

    //提供一个全局访问点,用于获取单例实例
    public static Singleton getInstance(){

        return SingletonHolder.singleton;
    }

    //jdk自动调用该方法,返回单例实例
    //防止反序列化时创建新实例
    protected Object readResolve(){
        //返回单例实例
        return SingletonHolder.singleton;
    }
}
